<template>
  <div class="menuAdd" v-loading="detailInfoShow">
    <!-- 筛选按钮 -->
    <div class="search-button" v-if="!contactAddShow">
      <el-button
        v-if="pageType !== 'detail'"
        class="btn save"
        @click="handleAddSave(menuFormRef)"
        ><el-icon class="icon" color="#fff"> <Tickets /> </el-icon
        >保存</el-button
      >
      <el-button class="btn direction" @click="handleBack"
        ><el-icon class="icon" color="#fff"> <Back /> </el-icon
        >返回</el-button
      >
    </div>
    <el-collapse v-model="activeNames">
      <!-- 基础信息 -->
      <el-collapse-item
        name="1"
        v-if="!contactAddShow"
        :class="contactAddShow ? 'customInfoUpClass' : 'customInfoDownClass'"
      >
        <template #title>
          <span class="circle"></span>
          <span class="collapse-title"
            >{{
              pageType === "detail" ? "" : pageType === "add" ? "新增" : "编辑"
            }}菜单信息</span
          >
        </template>
        <div class="menu-info">
          <el-form
            :model="menuForm"
            ref="menuFormRef"
            :rules="queryRules"
            label-width="100"
            v-enterToNext
            :disabled="pageType === 'detail'"
          >
            <el-row>
              <el-col :span="6">
                <el-form-item label="上级菜单">
                  <el-tree-select
                    ref="refSelect"
                    v-model="menuForm.parentId"
                    :data="menuOptions"
                    :props="{
                      value: 'menuId',
                      label: 'menuName',
                      children: 'children',
                    }"
                    value-key="menuId"
                    placeholder="选择上级菜单"
                    check-strictly
                  />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="菜单类型" prop="menuType">
                  <el-radio-group v-model="menuForm.menuType">
                    <el-radio label="M">目录</el-radio>
                    <el-radio label="C">菜单</el-radio>
                    <el-radio label="F">按钮</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col :span="6" v-if="menuForm.menuType != 'F'">
                <el-form-item label="菜单图标" prop="icon">
                  <el-popover
                    placement="bottom-start"
                    :width="540"
                    v-model:visible="showChooseIcon"
                    trigger="click"
                    @show="showSelectIcon"
                  >
                    <template #reference>
                      <el-input
                        v-model="menuForm.icon"
                        placeholder="点击选择图标"
                        @blur="showSelectIcon"
                        v-click-outside="hideSelectIcon"
                        readonly
                      >
                        <template #prefix>
                          <svg-icon
                            v-if="menuForm.icon"
                            :icon-class="menuForm.icon"
                            class="el-input__icon"
                            style="height: 32px; width: 16px"
                          />
                          <el-icon v-else style="height: 32px; width: 16px"
                            ><search
                          /></el-icon>
                        </template>
                      </el-input>
                    </template>
                    <icon-select
                      ref="iconSelectRef"
                      @selected="selected"
                      :active-icon="menuForm.icon"
                    />
                  </el-popover>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="菜单名称" prop="menuName">
                  <el-input
                    v-model="menuForm.menuName"
                    placeholder="请输入菜单名称"
                  />
                </el-form-item>
              </el-col>
              <!-- </el-row>
            <el-row> -->
              <el-col :span="6">
                <el-form-item label="显示排序" prop="orderNum">
                  <el-input-number
                    v-model="menuForm.orderNum"
                    controls-position="right"
                    :min="0"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="6" v-if="menuForm.menuType != 'F'">
                <el-form-item>
                  <template #label>
                    <span>
                      <el-tooltip
                        content="选择是外链则路由地址需要以`http(s)://`开头"
                        placement="top"
                      >
                        <el-icon><question-filled /></el-icon> </el-tooltip
                      >是否外链
                    </span>
                  </template>
                  <el-radio-group v-model="menuForm.isFrame">
                    <el-radio label="0">是</el-radio>
                    <el-radio label="1">否</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col :span="6" v-if="menuForm.menuType != 'F'">
                <el-form-item prop="path">
                  <template #label>
                    <span>
                      <el-tooltip
                        content="访问的路由地址，如：`user`，如外网地址需内链访问则以`http(s)://`开头"
                        placement="top"
                      >
                        <el-icon><question-filled /></el-icon>
                      </el-tooltip>
                      路由地址
                    </span>
                  </template>
                  <el-input
                    v-model="menuForm.path"
                    placeholder="请输入路由地址"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="6" v-if="menuForm.menuType == 'C'">
                <el-form-item prop="component">
                  <template #label>
                    <span>
                      <el-tooltip
                        content="访问的组件路径，如：`system/user/index`，默认在`views`目录下"
                        placement="top"
                      >
                        <el-icon><question-filled /></el-icon>
                      </el-tooltip>
                      组件路径
                    </span>
                  </template>
                  <el-input
                    v-model="menuForm.component"
                    placeholder="请输入组件路径"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="6" v-if="menuForm.menuType != 'M'">
                <el-form-item>
                  <el-input
                    v-model="menuForm.perms"
                    placeholder="请输入权限标识"
                    maxlength="100"
                  />
                  <template #label>
                    <span>
                      <el-tooltip
                        content="控制器中定义的权限字符，如：@PreAuthorize(`@ss.hasPermi('system:user:list')`)"
                        placement="top"
                      >
                        <el-icon><question-filled /></el-icon>
                      </el-tooltip>
                      权限字符
                    </span>
                  </template>
                </el-form-item>
              </el-col>
              <el-col :span="6" v-if="menuForm.menuType == 'C'">
                <el-form-item>
                  <el-input
                    v-model="menuForm.query"
                    placeholder="请输入路由参数"
                    maxlength="255"
                  />
                  <template #label>
                    <span>
                      <el-tooltip
                        content='访问路由的默认传递参数，如：`{"id": 1, "name": "ry"}`'
                        placement="top"
                      >
                        <el-icon><question-filled /></el-icon>
                      </el-tooltip>
                      路由参数
                    </span>
                  </template>
                </el-form-item>
              </el-col>
              <el-col :span="6" v-if="menuForm.menuType == 'C'">
                <el-form-item>
                  <template #label>
                    <span>
                      <el-tooltip
                        content="选择是则会被`keep-alive`缓存，需要匹配组件的`name`和地址保持一致"
                        placement="top"
                      >
                        <el-icon><question-filled /></el-icon>
                      </el-tooltip>
                      是否缓存
                    </span>
                  </template>
                  <el-radio-group v-model="menuForm.isCache">
                    <el-radio label="0">缓存</el-radio>
                    <el-radio label="1">不缓存</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col :span="6" v-if="menuForm.menuType != 'F'">
                <el-form-item>
                  <template #label>
                    <span>
                      <el-tooltip
                        content="选择隐藏则路由将不会出现在侧边栏，但仍然可以访问"
                        placement="top"
                      >
                        <el-icon><question-filled /></el-icon>
                      </el-tooltip>
                      显示状态
                    </span>
                  </template>
                  <el-radio-group v-model="menuForm.visible">
                    <el-radio
                      v-for="dict in sys_show_hide"
                      :key="dict.value"
                      :label="dict.value"
                      >{{ dict.label }}</el-radio
                    >
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item>
                  <template #label>
                    <span>
                      <el-tooltip
                        content="选择停用则路由将不会出现在侧边栏，也不能被访问"
                        placement="top"
                      >
                        <el-icon><question-filled /></el-icon>
                      </el-tooltip>
                      菜单状态
                    </span>
                  </template>
                  <el-radio-group v-model="menuForm.status">
                    <el-radio
                      v-for="dict in sys_normal_disable"
                      :key="dict.value"
                      :label="dict.value"
                      >{{ dict.label }}</el-radio
                    >
                  </el-radio-group>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
      </el-collapse-item>
    </el-collapse>
  </div>
</template>

<script setup>
// import { addMenu, getMenu, updateMenu } from "@/api/system/menu";
import {
  addMenu,
  delMenu,
  getMenu,
  listMenu,
  updateMenu,
} from "@/api/system/menu";

const { proxy } = getCurrentInstance();
const { sys_normal_disable, sys_show_hide } = proxy.useDict(
  "sys_show_hide",
  "sys_normal_disable"
);
import { getDictsApi } from "@/api/dict";
import { ElMessage, ElMessageBox } from "element-plus";
import SvgIcon from "@/components/SvgIcon";
import IconSelect from "@/components/IconSelect";
import { ClickOutside as vClickOutside } from "element-plus";
const emit = defineEmits([
  "menuAddShow",
  "update:menuAddShow",
  "updateEvaluateAddShow",
  "refreshList",
]);
const props = defineProps({
  pageType: {
    type: String,
    default: "add",
  },
});
const activeNames = ref(["1", "2", "3"]);
const menuFormRef = ref();
const detailInfoShow = ref(false);
const menuOptions = ref([]);
const menuRef = ref(null);
const showChooseIcon = ref(false);
const iconSelectRef = ref(null);

const refSelect = ref();
const menuFormTemplate = {
  menuId: undefined,
  parentId: 0,
  menuName: undefined,
  icon: undefined,
  menuType: "M",
  orderNum: undefined,
  isFrame: "1",
  isCache: "0",
  visible: "0",
  status: "0",
};
const data = reactive({
  menuForm: JSON.parse(JSON.stringify(menuFormTemplate)),
  queryRules: {
    menuName: [
      { required: true, message: "菜单名称不能为空", trigger: "blur" },
    ],
    orderNum: [
      { required: true, message: "菜单顺序不能为空", trigger: "blur" },
    ],
    path: [{ required: true, message: "路由地址不能为空", trigger: "blur" }],
  },
  contactTypeList: [],
  templateList: [],
  provinceList: [],
  cityList: [],
  areaList: [],
  userList: [],
  deptList: [],
});
const { menuForm, queryRules, templateList } = toRefs(data);
const contactAddShow = ref(false);

// /** 查询菜单树结构 */
// function getMenuTreeselect() {
//   menuTreeselect().then((response) => {
//     menuOptions.value = response.data;
//   });
// }

/** 展示下拉图标 */
function showSelectIcon() {
  iconSelectRef.value.reset();
  showChooseIcon.value = true;
}
/** 选择图标 */
function selected(name) {
  menuForm.value.icon = name;
  showChooseIcon.value = false;
}
/** 图标外层点击隐藏下拉列表 */
function hideSelectIcon(event) {
  var elem =
    event.relatedTarget ||
    event.srcElement ||
    event.target ||
    event.currentTarget;
  var className = elem.className;
  if (className !== "el-input__inner") {
    showChooseIcon.value = false;
  }
}

/** 查询菜单下拉树结构 */
function getTreeselect() {
  menuOptions.value = [];
  listMenu().then((response) => {
    const menu = { menuId: 0, menuName: "主类目", children: [] };
    menu.children = proxy.handleTree(response.data, "menuId");
    menuOptions.value.push(menu);
  });
}

// 保存
const handleAddSave = async (menuFormRef) => {
  if (!menuFormRef) return;
  await menuFormRef.validate(async (valid, fields) => {
    if (valid) {
      ElMessageBox.confirm("确定保存以上数据吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        confirmButtonClass: "confirmBtnClass",
        cancelButtonClass: "cancelBtnClass",
      })
        .then(async () => {
          if (menuForm.value.menuId != undefined) {
            updateMenu(menuForm.value).then((res) => {
              emit("update:menuAddShow", false);
              emit("refreshList", true);
              ElMessage.success("操作成功");
              menuForm.value = JSON.parse(JSON.stringify(menuFormTemplate));
            });
          } else {
            addMenu(menuForm.value).then((res) => {
              emit("update:menuAddShow", false);
              emit("refreshList", true);
              ElMessage.success("操作成功");
              menuForm.value = JSON.parse(JSON.stringify(menuFormTemplate));
            });
          }
        })
        .catch(() => {});
    } else {
      console.log("error submit!");
    }
  });
};

// 返回
const handleBack = () => {
  if (props.pageType === "detail") {
    emit("updateEvaluateAddShow", false);
    emit("update:menuAddShow", false);
    menuForm.value = JSON.parse(JSON.stringify(menuFormTemplate));
  } else {
    ElMessageBox.confirm("确定返回上一级吗?以上数据未保存将会丢失!", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
      confirmButtonClass: "confirmBtnClass",
      cancelButtonClass: "cancelBtnClass",
    })
      .then(async () => {
        emit("updateEvaluateAddShow", false);
        emit("update:menuAddShow", false);
        menuForm.value = JSON.parse(JSON.stringify(menuFormTemplate));
      })
      .catch(() => {});
  }
};

async function getDicts() {
  await getDictsApi("contract_template_type").then((res) => {
    // 模板
    if (res.code === 200) {
      templateList.value = res.data;
    }
  });
}

// 处理父id
const handleParentId = (id) => {
  if (id) {
    menuForm.value.parentId = id;
  } else {
    menuForm.value.parentId = 0;
  }
};

// 处理详情信息
const handleDetailInfo = async (menuId) => {
  try {
    detailInfoShow.value = true;
    getMenu(menuId).then((response) => {
      menuForm.value = response.data;
      detailInfoShow.value = false;
    });
  } catch (error) {
    detailInfoShow.value = false;
  }
};

onMounted(() => {
  getDicts();
  getTreeselect();
  // getMenuTreeselect();
  // if (props.pageType === "add") {
  nextTick(() => {
    refSelect.value.focus(); // 聚焦
  });
  // }
});

defineExpose({
  handleDetailInfo,
  handleParentId,
});
</script>
<style lang="scss" scoped>
:deep(.el-collapse-item__header) {
  background-color: #f8faff;
}
.menuAdd {
  padding: 20px 20px;
  width: 100%;
  height: 100%;
  :deep(.el-date-editor.el-input, .el-date-editor.el-input__wrapper) {
    width: 268px !important;
    height: 34px !important;
  }
  /* .search-button {
    position: fixed;
    top: 110px;
    right: 60px;
    display: flex;
    .btn {
      display: flex;
      justify-content: center;
      align-items: center;
      width: 90px;
      height: 34px;
      padding: 10px;
      // margin-right: 20px;
      font-size: 14px;
      border-radius: 4px;
      user-select: none;
      cursor: pointer;
    }
    .btn.save {
      color: #fff;
      background: rgba(67, 207, 124, 1);
      border: none;
      &:hover {
        background: rgba(67, 207, 124, 0.85);
      }
    }

    .btn.add {
      .btn.add {
        border: none;
        color: #fff;
        background: rgba(255, 159, 0, 1);
        &:hover {
          background: rgba(255, 159, 0, 0.85);
        }
      }
    }

    .btn.back {
      border: none;
      color: #fff;
      background: rgba(255, 159, 0, 1);
      &:hover {
        background: rgba(255, 159, 0, 0.85);
      }
    }
    .btn.direction {
      border: none;
      color: #fff;
      background: rgba(153, 153, 153, 1);
      &:hover {
        background: rgba(153, 153, 153, 0.85);
      }
    }

    .icon {
      margin-right: 6px;
    }
  } */
  .circle {
    margin: 0 10px 0 20px;
    width: 6px;
    height: 6px;
    background: #007cef;
    border-radius: 50%;
  }
  .collapse-title {
    font-weight: bold;
    font-size: 16px;
  }
  .el-collapse,
  .el-collapse-item__wrap {
    border: none;
  }

  .search-input {
    width: 268px;
    height: 34px;
  }
  .menu-info {
    padding: 20px 10px 5px 10px;
    background-color: #fafafa;
    margin: 10px 0;
  }
  .contact-info {
    padding-top: 20px;
    .table-operate {
      display: flex;
      justify-content: space-around;
      .table-icon {
        width: 20px;
        height: 20px;
        cursor: pointer;
      }
    }
  }
  .button-position {
    top: 6px;
    right: 30px;
  }
  :deep(.el-input__inner) {
    height: 34px;
  }
  .customInfoUpClass {
    -webkit-animation: customInfoDown 0.8s ease-out;
  }
  .customInfoDownClass {
    -webkit-animation: customInfoDown 0.8s ease-out;
  }

  .contactInfoUpClass {
    -webkit-animation: contactInfoUp 0.8s ease-out;
  }
  .contactInfoDownClass {
    -webkit-animation: contactInfoUp 0.8s ease-out;
  }
  @-webkit-keyframes customInfoUp {
    0% {
      opacity: 0;
      -webkit-transform: translateY(80px);
    }

    100% {
      opacity: 1;
      -webkit-transform: translateY(0px);
    }
  }
  @-webkit-keyframes customInfoDown {
    0% {
      opacity: 0;
      -webkit-transform: translateY(-80px);
    }

    100% {
      opacity: 1;
      -webkit-transform: translateY(0px);
    }
  }
  @-webkit-keyframes contactInfoUp {
    0% {
      opacity: 0;
      -webkit-transform: translateY(80px);
    }

    100% {
      opacity: 1;
      -webkit-transform: translateY(0px);
    }
  }
}
</style>
